//网络请求工具类
//引入头文件
let common_js = require('/common.js');
let en_js = require('/environment.js');
let url_js = require('/url.js');
let user_js = require('/user.js');
let const_js = require('/const.js');
let notificationCenter = require('../thridLib/WxNotificationCenter.js');

//微信小程序网络请求封装
function wxRequest(url, datas, config, resolve, reject) {
  let promise = new Promise((resolve, reject) => {
    //1.数据
    let {
      contentType = 'application/json',
        method = 'POST',
        showLoading = true,
        ...other
    } = {
      ...config
    }
    //2.是否显示加载框
    if (showLoading) {
      common_js.showLoading();
    }
    //3.网络请求
    wx.request({
      url: en_js.baseUrl + url,
      data: {
        ...datas
      },
      method: method,
      header: {
        'content-type': contentType,
        'Access-Token': user_js.getCode()
      },
      success: res => {
        if (showLoading) {
          common_js.hideLoading();
        }
        //正常情况下
        if (common_js.validResponse(res)) {
          setTimeout(function() {
            resolve(res.data);
          }, 268);
        } else if (parseInt(res.data.code) == 610) {
          //长时间未登录，登录失效，重新获取code
          handleLongTimeNoLogin();
          setTimeout(function () {
            reject(res);
          }, 268);
        } else {
          let sysMsg = common_js.responseMsg(res);
          common_js.showToast(sysMsg);
          setTimeout(function() {
            reject(res);
          }, 268);
        }
      },
      fail: err => {
        if (showLoading) {
          common_js.hideLoading();
        }
        common_js.showToast(err.errMsg);
        setTimeout(function() {
          reject(err);
        }, 268);
      }
    });
  });
  return promise;
}


//微信小程序网络请求封装
function wxRequest2(url, datas, config, resolve, reject) {
  let promise = new Promise((resolve, reject) => {
    //1.数据
    let {
      contentType = 'application/json',
        method = 'GET',
        showLoading = true,
        ...other
    } = {
      ...config
    }
    //2.是否显示加载框
    if (showLoading) {
      common_js.showLoading();
    }
    //3.网络请求
    wx.request({
      url: en_js.baseUrl + url,
      data: {
        ...datas
      },
      method: method,
      header: {
        'content-type': contentType,
        'Access-Token': user_js.getCode()
      },
      success: res => {
        if (showLoading) {
          common_js.hideLoading();
        }
        //正常情况下
        if (common_js.validResponse(res)) {
          setTimeout(function() {
            resolve(res.data);
          }, 268);
        } else if (parseInt(res.data.code) == 610) {
          //长时间未登录，登录失效，重新获取code
          handleLongTimeNoLogin();
        } else {
          let sysMsg = common_js.responseMsg(res);
          common_js.showToast(sysMsg);
          setTimeout(function() {
            reject(res);
          }, 268);
        }
      },
      fail: err => {
        if (showLoading) {
          common_js.hideLoading();
        }
        common_js.showToast(err.errMsg);
        setTimeout(function() {
          reject(err);
        }, 268);
      }
    });
  });
  return promise;
}

//下载接口
function wxDownloadFile(url, config, resolve, reject) {
  let promise = new Promise((resolve, reject) => {

    let {
      showLoading = true,
        ...other
    } = {
      ...config
    }
    //是否显示加载框
    if (showLoading) {
      common_js.showLoading();
    }
    wx.downloadFile({
      url: url,
      success: res => {
        //解析用户信息获取UnionId
        if (res.statusCode == 200) {
          setTimeout(function() {
            resolve(res.tempFilePath);
          }, 268);
        } else {
          var errorMsg = res.errMsg;
          common_js.showToast(errorMsg);
          setTimeout(function() {
            reject(res);
          }, 268);
        }
        if (showLoading) {
          common_js.hideLoading();
        }
      },
      fail: err => {
        if (showLoading) {
          common_js.hideLoading();
        }
        common_js.showToast(err.errMsg);
        setTimeout(function() {
          reject(err);
        }, 268);
      }
    })
  });
  return promise;
}

// 处理长时间未登录的情况
function handleLongTimeNoLogin() {
  //重新获取code
  getAccessToken();
}

//***************/
//获取网络请求使用的code
function getAccessToken() {
  //重新登录
  wx.login({
    success: res => {
      if (res.code) {
        //发起网络请求
        loginRecordRequest(res.code);
      } else {
        common_js.showModal('登录失败！' + res.errMsg, null, null, null, null, () => {
          //重新获取code
          getAccessToken();
        })
      }
    }
  });
}

//记录微信的code并返回openid
function loginRecordRequest(loginCode) {
  var data = {
    code: loginCode
  };
  wxRequest(url_js.loginRecordUrl, data).then(res => {
    var userObj = user_js.userInfo();
    if (!userObj) {
      userObj = {};
      userObj.role = -1; //授权用户为0
    }
    userObj.code = loginCode;
    userObj.openId = res.result;
    //save
    user_js.saveUserInfo(userObj);
    //发送通知
    notificationCenter.postNotificationName(const_js.getCodeSucessNoti);
  }).catch(err => {
    common_js.showModal('登录失败！' + res.errMsg, null, null, null, null, () => {
      //重新获取code
      getAccessToken();
    })
    common_js.log(err);
  });
}
//***************/

module.exports = {
  wxRequest: wxRequest,
  wxRequest2: wxRequest2,
  wxDownloadFile: wxDownloadFile,
  getAccessToken: getAccessToken
}